<template>
  <div class="login">
    <div class="login-container">
      <!-- 登录表单区域 -->
      <!-- ref="loginFormRef" 获取表单的引用对象 -->
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules">
        <h1>租房系统</h1>
        <!-- 用户名 -->
     <el-form-item prop="username">
    <el-input
    placeholder="用户名"
    prefix-icon="el-icon-user-solid" v-model="loginForm.username" class="username" >
  </el-input>
  </el-form-item>
  <!-- 密码 -->
  <el-form-item prop="password">
    <el-input
    placeholder="密码"
    prefix-icon="iconfont icon-mima1" v-model="loginForm.password" class="pwd" type="password">
  </el-input>
  </el-form-item>
  <!-- 按钮 -->
  <el-form-item class="login-btn">
    <el-button type="primary" @click="login">登录</el-button>
    <el-button type="info" @click="resetLoginForm">重置</el-button>
  </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name:"Login",
  data(){
    return{
      loginForm:{
        username:'admin',
        password:'123456'
      },
      loginFormRules:{
        //验证用户名是否符合规则
      username:[
         { required: true, message: '请输入用户名', trigger: 'blur' },
         { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
      ],
      //验证密码是否符合规则
      password:[
        { required: true, message: '请输入用户名', trigger: 'blur' },
         { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
      ]
    }
    }
    
  },
  methods:{
    //重置表单中的用户名和密码
    resetLoginForm(){
      this.$refs.loginFormRef.resetFields();
    },
    //登录之前表单的预验证
    login(){
      this.$refs.loginFormRef.validate(async valid =>{
        if(!valid) return;
        const { data:res }=await this.$http.post("login",this.loginForm);
        if(res.meta.status !==200) return this.$message.error("登录失败");
        this.$message.success("登录成功");
        //1.将登录之后的token保存到客户端的sessionStorage中
        //项目中除了登录之外的其他API接口 必须在登录之后才能访问
        //token只应在当前网站打开期间生效，所以将token保存在sessionStorage中
        window.sessionStorage.setItem("token",res.data.token);
        this.$router.push('/home')
      });
    }
  }
}
</script>

<style scoped>
.login{
  background: url(../assets/img/17.jpg) no-repeat;
  background-size: cover;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

}
.login-container{
  width: 500px;
  height: 400px;
  background:rgba(0, 0, 0, 0.3);
  border-radius: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.username,
.pwd{
  width: 350px;
  outline: none;
}
.login .login-container h1{
  font-size: 30px;
  color: white;
  text-align: center;
  margin-bottom: 55px
}
.login-btn{
  display: flex;
  justify-content: center;
}
</style>